package com.pj.android.brower.util;

import android.content.Context;
import android.content.pm.ApplicationInfo;

import com.alibaba.fastjson.JSON;
import com.pj.android.brower.business.bean.UpdateInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Created by hHui on 2019/1/21 0021.
 * <p>
 * 读取META-INF 下的文件
 */
public class MetaInfUtils {

    public static UpdateInfo getUpdatePackage(Context context) {
        ApplicationInfo appInfo = context.getApplicationInfo();
        String sourceDir = appInfo.sourceDir;
        ZipFile zipfile = null;
        try {
            zipfile = new ZipFile(sourceDir);
            Enumeration<?> entries = zipfile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String entryName = entry.getName();
                if (entryName.contains("../")) break;
                if (entryName.startsWith("META-INF/config.txt")) {
                    long size = entry.getSize();
                    if (size > 0) {
                        BufferedReader br = new BufferedReader(new InputStreamReader(zipfile.getInputStream(entry)));
                        StringBuffer buffer = new StringBuffer();
                        String line = br.readLine();
                        while (line != null) {
                            buffer.append(line);
                            buffer.append("\n");
                            line = br.readLine();
                        }
                        br.close();
                        return JSON.parseObject(buffer.toString(), UpdateInfo.class);
                    }
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
